package com.hpe.aruba.CPPM.dialogs;

import android.app.AlertDialog;
import android.content.Context;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.hpe.aruba.CPPM.Data;
import com.hpe.aruba.CPPM.R;
import com.hpe.aruba.CPPM.interfaces.JsonInterface;
import com.hpe.aruba.CPPM.interfaces.MacListActivity;
import com.hpe.aruba.CPPM.objects.Device;
import com.hpe.aruba.CPPM.utils.ClearpassUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

public class MacAdressDialog implements JsonInterface {

    private final AlertDialog dialogBuilder;
    private final View dialogView;
    private MacListActivity context;
    private ClearpassUtils clearpassUtils;
    private RequestQueue requestQueue;
    /*to compare when hitting save*/
    private String noteBackup;
    private String statusBackup;
    private String nameBackup;
    private String vendorBackup;

    public MacAdressDialog(MacListActivity context, Device mac) {
        this.context = context;

        dialogBuilder = new AlertDialog.Builder((Context) context).create();
        LayoutInflater inflater = context.getLayoutInflater();
        dialogView = inflater.inflate(R.layout.mac_attribute_dialog, null);

        initFields(mac);
    }

    private void initFields(Device device) {
        requestQueue = Volley.newRequestQueue(dialogView.getContext());
        clearpassUtils = new ClearpassUtils(requestQueue);

        //CheckBox checkBox;
        EditText name = dialogView.findViewById(R.id.detail_name);
        EditText mac = dialogView.findViewById(R.id.detail_mac);
        EditText vendor = dialogView.findViewById(R.id.detail_vendor);
        Spinner roleSpinner = dialogView.findViewById(R.id.detail_role);
        Spinner statusSpinner = dialogView.findViewById(R.id.detail_status);
        EditText notes = dialogView.findViewById(R.id.detail_notes);


        Button button1 = dialogView.findViewById(R.id.buttonSubmit);
        Button button2 = dialogView.findViewById(R.id.buttonCancel);

        button2.setOnClickListener(view -> dialogBuilder.dismiss());
        button1.setOnClickListener(view -> {
            String newNotes = notes.getText().toString();

            JSONObject patch = new JSONObject();
            String kind = "device";
            try {
                /*endpoint only*/
                if (device.isEndpoint()) {
                    kind = "endpoint";
                    String newStatus = statusSpinner.getSelectedItem().toString();
                    putIfUnequal(patch, "status", statusBackup, newStatus);
                    putIfUnequal(patch, "description", noteBackup, newNotes);
                } else {
                    String newName = name.getText().toString();
                    putIfUnequal(patch, "name", nameBackup, newName);
                    String newVendor = vendor.getText().toString();
                    putIfUnequal(patch, "vendor", vendorBackup, newVendor);
                    putIfUnequal(patch, "notes", noteBackup, newNotes);
                }
            } catch (JSONException e) {
                Toast.makeText(dialogView.getContext(), R.string.error_save_unknown,
                        Toast.LENGTH_LONG).show();
                return;
            }
            clearpassUtils.patchEndpointOrDevice(kind, device.getMac(), patch, context, this);
        });

        name.setText(device.getName());
        mac.setText(device.getMac());
        mac.setEnabled(!device.isImported()); /*if it is imported, disable editing*/
        vendor.setText(device.getVendor());
        notes.setText(device.getNotes());

        noteBackup = device.getNotes(); /*backup*/
        if (!device.isEndpoint()) {
            nameBackup = device.getName();
            vendorBackup = device.getVendor();
        }

        /*role spinner*/
        if (Data.roles != null) {
            int position = 0;
            for (int i = 0; i < Data.roles.size(); i++) {
                if (Data.roles.get(i).getName().equals(device.getRole_name())) {
                    position = i;
                }
            }
            ArrayAdapter roleAdapter = new ArrayAdapter(dialogView.getContext(), android.R.layout.simple_spinner_item, Data.roles);
            roleAdapter.setDropDownViewResource(android.R.layout
                    .simple_spinner_dropdown_item);
            roleSpinner.setAdapter(roleAdapter);
            roleSpinner.setSelection(position);
        }
        roleSpinner.setEnabled(false); /*role editing not supported -> role mapping mess, as well as checking for authorization*/


        if (device.isEndpoint()) {
            /*location*/
            EditText location = dialogView.findViewById(R.id.detail_location);
            location.setText(device.getLast_known_location());
            location.setEnabled(false);
            /*time*/
            EditText time = dialogView.findViewById(R.id.detail_time);
            java.text.DateFormat dateFormat = /*get date format of user locale*/
                    android.text.format.DateFormat.getDateFormat(dialogView.getContext());
            String s = dateFormat.format(new Date (device.getUpdated_at())); /*localize time*/
            time.setText(s);
            time.setEnabled(false);
            /*hide guest properties*/
            TableRow vendorRow = dialogView.findViewById(R.id.vendorRow);
            TableRow nameRow = dialogView.findViewById(R.id.nameRow);
            TableRow roleRow = dialogView.findViewById(R.id.roleRow);
            vendorRow.setVisibility(View.GONE);
            nameRow.setVisibility(View.GONE);
            roleRow.setVisibility(View.GONE);

            /*status spinner*/
            ArrayAdapter statusAdapter = ArrayAdapter.createFromResource(dialogView.getContext(),
                    R.array.statuses, android.R.layout.simple_spinner_item);
            statusAdapter.setDropDownViewResource(android.R.layout
                    .simple_spinner_dropdown_item);
            statusSpinner.setAdapter(statusAdapter);
            statusSpinner.setSelection(getIndexInStringArray(R.array.statuses, device.getStatus()));
            statusBackup = device.getStatus();
        } else {
            TableRow statusRow = dialogView.findViewById(R.id.statusRow);
            statusRow.setVisibility(View.GONE);
            TableRow locationRow = dialogView.findViewById(R.id.locationRow);
            locationRow.setVisibility(View.GONE);
            TableRow timeRow = dialogView.findViewById(R.id.timeRow);
            timeRow.setVisibility(View.GONE);
        }
    }

    public void apply(JSONObject jsonObject) {
        if (jsonObject == null) { /*null on error*/
            Toast.makeText(dialogView.getContext(), R.string.error_save_unknown, Toast.LENGTH_LONG).show();
        } else {
            dialogBuilder.dismiss();
        }
    }

    public void show() {
        dialogBuilder.setView(dialogView);
        dialogBuilder.show();
    }

    private int getIndexInStringArray(int stringArrId, String aString) {
        String[] stringArr = dialogView.getResources().getStringArray(stringArrId);
        for (int x = 0; x < stringArr.length; x++) {
            if (stringArr[x].equals(aString)) return x;
        }
        return -1;
    }

    private void putIfUnequal(JSONObject jsonObject, String key, String _old, String _new) throws JSONException {
        if (!_old.equals(_new)) {
            jsonObject.put(key, _new);
        }
    }

}
